package com.group56.view.userend.book_module;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


import com.group56.GymApp;
import com.group56.factory.AppCMFactory;
import com.group56.model.entity.Coach;
import com.group56.model.entity.Schedule;
import com.group56.model.tools.jsonFileProcessor;
import com.group56.utils.DBSrcMenu;
import com.group56.utils.FXMLSrcMenu;
import com.group56.utils.FXMLViewHandler;
import com.group56.view.FrameworkController;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;

import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

public class CoachDetailController implements Initializable {
    private String time;
    public  static String coachID;
    public Map<String,Integer> map;
    public SimpleDateFormat s;
    public String[] context;
    public static String choosetime;
    public static  int count=0;
    public int[] list;

    @FXML
    public Label name;
    public Label gender;
    public Label tel;
    public Label infor;
    public Button book_button;
    public Button video_button;
    public HBox choosebox;
    public FlowPane inforpane;
    public ChoiceBox dateBox;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        s = new SimpleDateFormat("yyyy.MM.dd");
        if(CoachDetailController.count==0){
            Calendar cal = new GregorianCalendar();
            cal.setTime(new Date());
            cal.add(cal.DATE,1);
            CoachDetailController.choosetime=s.format(cal.getTime());
        }
        CoachDetailController.count++;
        list=new int[8];
        map=new HashMap<String,Integer>();
        map.put("9:00-10:00",0);
        map.put("10:00-11:00",1);
        map.put("11:00-12:00",2);
        map.put("14:00-15:00",3);
        map.put("15:00-16:00",4);
        map.put("16:00-17:00",5);
        map.put("19:30-20:30",6);
        map.put("20:30-21:30",7);


        jsonFileProcessor file = new jsonFileProcessor(DBSrcMenu.SCHEDULE_JSON.getSrc());
        StringBuffer buffer = file.read();
        if (!buffer.toString().equals("")) {
            ArrayList<Schedule> schedules = new Gson().fromJson(buffer.toString(), new TypeToken<ArrayList<Schedule>>(){}.getType());
            for (Schedule c : schedules){
                if(c.getCoachID().equals(coachID)&&c.getDate().equals(CoachDetailController.choosetime)){
                    list[map.get(c.getTime())]=1;
                }
            }
        }
        for(int i=0;i<8;i++){
            if(list[i]==0)
                choosebox.getChildren().add(addButton(i));
            else{
                Button btn=new Button("Booked");
                btn.getStyleClass().add("button1");
                choosebox.getChildren().add(btn);
            }
        }


        Calendar cal1 = new GregorianCalendar();
        context=new String[3];
        cal1.setTime(new Date());
        for(int j=0;j<3;j++){
            cal1.add(cal1.DATE,1);
            context[j]=s.format(cal1.getTime());
        }
        dateBox.setItems(FXCollections.observableArrayList(context[0],context[1],context[2]));


        jsonFileProcessor file1 = new jsonFileProcessor(DBSrcMenu.COACH_JSON.getSrc());
        StringBuffer buffer1 = file1.read();
        if (!buffer1.toString().equals("")) {
            ArrayList<Coach> records = new Gson().fromJson(buffer1.toString(), new TypeToken<ArrayList<Coach>>(){}.getType());
            System.out.println(records);
            for (Coach c : records) {
                System.out.println(c);
                if (c.getCoachID().equals(coachID)) {
                    VBox box = new VBox();
                    box.setMinWidth(20);
                    String string = c.getPicUrl();
                    System.out.println(string);
                    Image image = new Image(string);
                    ImageView pic = new ImageView();
                    pic.setImage(image);
                    pic.setFitHeight(240);
                    pic.setFitWidth(240);
                    inforpane.getChildren().add(0, box);
                    inforpane.getChildren().add(1, pic);
                    name.setText(c.getName());
                    gender.setText(c.getSex());
                    tel.setText(c.getTele());
                    infor.setText(c.getDetail());
                    break;
                }
            }
        }
    }
    public void chooseDate(Event event) throws  IOException{

        String timeId=dateBox.getSelectionModel().selectedIndexProperty().toString();
        timeId=timeId.substring(timeId.length()-2,timeId.length()-1);
        CoachDetailController.choosetime=context[Integer.parseInt(timeId)];

        FrameworkController appFramework = (FrameworkController) AppCMFactory.getCtrlrMediator().getController(FXMLSrcMenu.UserEnd.APP_FRAMEWORK.getSrc());
        FXMLViewHandler.putViewInPane(appFramework.getContentPane(),FXMLViewHandler.getView(FXMLSrcMenu.UserEnd.COACH_DETAIL.getSrc()));
    }

    public void submit(Event event) throws IOException {
            jsonFileProcessor file = new jsonFileProcessor(DBSrcMenu.SCHEDULE_JSON.getSrc());
            StringBuffer buffer = file.read();
            if (!buffer.toString().equals("")) {
                ArrayList<Schedule> records = new Gson().fromJson(buffer.toString(), new TypeToken<ArrayList<Schedule>>() {}.getType());
                Schedule news=new Schedule();
                news.setCoachID(coachID);
                news.setCustomerID(GymApp.customerId);
                news.setScheduleID((records.size()+1)+"");
                news.setTime(time);
                news.setDate(CoachDetailController.choosetime);
                records.add(news);
                file.rewrite(records);
            }
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION,"successful booking");
            alert.show();
            alert.setOnCloseRequest((DialogEvent e) -> {
                FrameworkController appFramework = null;
                try {
                    appFramework = (FrameworkController) AppCMFactory.getCtrlrMediator().getController(FXMLSrcMenu.UserEnd.APP_FRAMEWORK.getSrc());
                    FXMLViewHandler.putViewInPane(appFramework.getContentPane(),FXMLViewHandler.getView(FXMLSrcMenu.UserEnd.SCHEDULE_LIST.getSrc()));
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            });
    }
    public void back(Event event) throws IOException{
        try {
            FrameworkController appFramework = null;
            appFramework = (FrameworkController) AppCMFactory.getCtrlrMediator().getController(FXMLSrcMenu.UserEnd.APP_FRAMEWORK.getSrc());
            FXMLViewHandler.putViewInPane(appFramework.getContentPane(),FXMLViewHandler.getView(FXMLSrcMenu.UserEnd.COACH_LIST.getSrc()));
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
    public void setTime(String time){
        this.time=time;
    }
    public Button addButton(int i){
        String text=null;
        for(String key: map.keySet()){
            if(map.get(key).equals(i)){
                text=key;
                break;
            }
        }
        Button btn=new Button(text);
        btn.setOnAction((ActionEvent e) -> {
            this.setTime(btn.getText());
            for(int j = 0; j <8; j++){
                Node node=choosebox.getChildren().get(j);
                if(node==btn)
                    btn.getStyleClass().add("button2");
                else if(list[j]==0){
                    btn.getStyleClass().add(0,"button1");
                }

            }
        });
        btn.getStyleClass().add("button1");
        return btn;
    }

}
